
#include "Mesh.h"
#include "OgreApp.h"

Entity *CreateMesh(const std::vector<Vector3> &vertices, const std::vector<Vector3i> &triangles)
{
	static uint number = 0;
	String num = StringConverter::toString(number++);

	String name = "Mesh" + num;
	String eName = "Entity" + num;
	
  MeshPtr msh = MeshManager::getSingleton().createManual(name, 
    ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);

  // Create SubMesh
  SubMesh* sm = msh->createSubMesh();
  sm->useSharedVertices = false;
  sm->vertexData = new VertexData();
  sm->vertexData->vertexStart = 0;
  sm->vertexData->vertexCount = vertices.size();
  
  // Set up vertex buffer
  VertexDeclaration* dcl = sm->vertexData->vertexDeclaration;
  size_t offset = 0;
  dcl->addElement(0, offset, VET_FLOAT3, VES_POSITION);
  offset += VertexElement::getTypeSize(VET_FLOAT3);
  //dcl->addElement(0, offset, VET_FLOAT3, VES_NORMAL);
  //offset += VertexElement::getTypeSize(VET_FLOAT3);
  
  // Create Vertex Buffer
  HardwareVertexBufferSharedPtr vbuf = HardwareBufferManager::getSingleton()
	  .createVertexBuffer(
    offset, vertices.size(), HardwareBuffer::HBU_STATIC_WRITE_ONLY);

  // Copy over vertex buffer data
  float* pReal = static_cast<float*>(vbuf->lock(HardwareBuffer::HBL_DISCARD));
  fori(vertices.size())
  {
    *pReal++ = vertices[i].x;
    *pReal++ = vertices[i].z;
    *pReal++ = vertices[i].y;
    
    //*pReal++ = vertices[i].x;
    //*pReal++ = vertices[i].z;
    //*pReal++ = vertices[i].y;
  }
  vbuf->unlock();
  
  // Set Vertex Buffer
  sm->vertexData->vertexBufferBinding->setBinding(0, vbuf);
  
  // Set up Index Buffer
  //sm->indexData->indexStart = 0;
  sm->indexData->indexCount = triangles.size()*3;
  sm->indexData->indexBuffer = HardwareBufferManager::getSingleton()
	  .createIndexBuffer(HardwareIndexBuffer::IT_32BIT, triangles.size()*3,
		  HardwareBuffer::HBU_STATIC_WRITE_ONLY);

  // Copy over index buffer data
  sm->indexData->indexBuffer->writeData(0, sizeof(Vector3i) * triangles.size(), &triangles[0], true);

	msh->load();

  Ogre::Entity *e = app->mSceneMgr->createEntity(eName, name);

	return e;
}